package utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;







import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

@SuppressWarnings("deprecation")
public class HttpHelper {
	private final String USER_AGENT = "Mozilla/5.0";
	private static String baseUrl = "https://jenkins.di2e.net/job/SED-CTV-paramBuild/buildWithParameters?token=TOKEN_NAME&BRANCH_NAME=";
	// "https://jenkins.di2e.net/user/stephen.matthai/my-views/view/CTV/job/SED-CTV-paramBuild/";

	// HTTP GET request
	public void sendGet() throws Exception {

		String url = baseUrl + "SEDCTV-69";

		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();
	 
			// optional default is GET
			con.setRequestMethod("GET");
	 
			//add request header
			con.setRequestProperty("User-Agent", USER_AGENT);
	 
			int responseCode = con.getResponseCode();
			System.out.println("\nSending 'GET' request to URL : " + url);
			System.out.println("Response Code : " + responseCode);
	 
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();
	 
			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
	 
			//print result
			System.out.println(response.toString());
	 
		}
	 
		// HTTP POST request
		public static void sendPost(String urlParams) throws Exception {
			String USER_AGENT = "Mozilla/5.0";
			// String baseUrl = "https://jenkins.di2e.net/job/SED-CTV-paramBuild/buildWithParameters" + urlParams;
			String baseUrl = "https://jenkins.di2e.net/job/SED-CTV-paramBuild/buildWithParameters?BRANCH_NAME=" + urlParams;
			// baseUrl = "https://jenkins.di2e.net/user/stephen.matthai/my-views/view/CTV/job/SED-CTV-paramBuild/build?token=sedctv&BRANCH_NAME=" + urlParams;
			baseUrl = "https://jenkins.di2e.net/job/SED-CTV-paramBuild/buildWithParameters?token=sedctv&BRANCH_NAME=SEDCTV-69";
			
			String url = baseUrl;
			URL obj = new URL(url);
			HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
	 
			//add request header
			con.setRequestMethod("POST");
			con.setRequestProperty("User-Agent", USER_AGENT);
			con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
			con.setRequestProperty("content-type",  "application/x-www-form-urlencoded");
	 
			String urlParameters = urlParams;
	 
			// Send post request
			con.setDoOutput(true);
			DataOutputStream wr = new DataOutputStream(con.getOutputStream());
			//wr.writeBytes(urlParameters);
			wr.flush();
			wr.close();
	 
			int responseCode = con.getResponseCode();
			System.out.println("\nSending 'POST' request to URL : " + url);
			System.out.println("Post parameters : " + urlParameters);
			System.out.println("Response Code : " + responseCode);
	 
			BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
			String inputLine;
			StringBuffer response = new StringBuffer();
	 
			while ((inputLine = in.readLine()) != null) {
				response.append(inputLine);
			}
			in.close();
	 
			//print result
			System.out.println(response.toString());
	 
		}


		public static boolean doPost(String url, String param) throws MalformedURLException, IOException {

			url = "https://jenkins.di2e.net/job/SED-CTV-paramBuild/buildWithParameters?token=sedctv&BRANCH_NAME=" + param;
			
			URL urlObj = new URL(url);
			URLConnection conn = urlObj.openConnection();
			conn.getInputStream().close();
//			PostMethod post = new PostMethod(url);
//            
//	        // execute method and handle any error responses.
//	        try {
//				InputStream in = post.getResponseBodyAsStream();
//			} catch (IOException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
	        
	        System.out.println("\n\nDOPOST\n\n");
	        
	        return true;
		}
		
		
		public static void doWork(String urlParams) throws IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
        	String baseUrl = "https://jenkins.di2e.net/job/SED-CTV-paramBuild/buildWithParameters?BRANCH_NAME=" + urlParams;
			// baseUrl = "https://jenkins.di2e.net/user/stephen.matthai/my-views/view/CTV/job/SED-CTV-paramBuild/build?token=sedctv&BRANCH_NAME=" + urlParams;
			baseUrl = "https://jenkins.di2e.net/job/SED-CTV-paramBuild/buildWithParameters?token=sedctv&BRANCH_NAME=SEDCTV-69";
			
			String url = baseUrl;
            HttpPost httppost = new HttpPost(url);
            httppost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
            
            System.out.println("Executing request: " + httppost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httppost);
            
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
            httpclient.close();
        }
    }
		
		public static void PostMe(String url) {

			CloseableHttpClient client = HttpClients.createDefault();
			HttpPost request = new HttpPost(url);
			request.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
			try {
				client.execute(request);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		public static void GetMe(String url) {

			CloseableHttpClient client = HttpClients.createDefault();
			HttpGet request = new HttpGet(url);
			request.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
			try {
				client.execute(request);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		/*
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;*/
		
		public static void anotherone(String url) throws ClientProtocolException, IOException {
			CloseableHttpClient httpclient = HttpClients.createDefault();
	        try {

	            HttpPost httpPost = new HttpPost(url);
	            List <org.apache.http.NameValuePair> nvps = new ArrayList <org.apache.http.NameValuePair>();
	            nvps.add(new org.apache.http.message.BasicNameValuePair("token", "sedctv"));
	            nvps.add(new org.apache.http.message.BasicNameValuePair("BRANCH_NAME", "SEDCT-69"));

	            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps);
	            httpPost.setEntity(formEntity);
	            
	            
	            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
	            CloseableHttpResponse response2 = httpclient.execute(httpPost);

	            try {
	                System.out.println(response2.getStatusLine());
	                HttpEntity entity2 = response2.getEntity();
	                // do something useful with the response body
	                // and ensure it is fully consumed
	                EntityUtils.consume(entity2);
	            } finally {
	                response2.close();
	            }
	        } finally {
	            httpclient.close();
	        }
	    }
}
